package com.kun.service;

import com.kun.common.Constants;
import com.kun.common.Result;
import com.kun.entity.Meta;
import com.kun.exception.MyServiceException;
import com.kun.mapper.MetaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MetaServiceImpl implements MetaService {

    @Autowired
    private MetaMapper metaMapper;

    @Override
    public Result addMeta(Meta meta) {
        if (StringUtils.isEmpty(meta.getName())){
            throw new MyServiceException(Constants.CODE_500,"业务异常,name属性不能为空");
        }else{
            HashMap<String, Object> map = new HashMap<>();
            map.put("name",meta.getName());
            if (metaMapper.selectAllMetas(map).size()>1){
                throw  new MyServiceException(Constants.CODE_600,"数据库异常,name属性重复");
            } else{
                metaMapper.addMeta(meta);
                return Result.success();
            }
        }
    }

    @Override
    public int deleteMeta(String name) {
        return metaMapper.deleteMeta(name);
    }

    @Override
    public int updateMeta(Meta meta,Map map) {
        return metaMapper.updateMeta(meta);
    }

    @Override
    public List<Meta> selectAllMetas(Map map) {
        if (map.containsKey("pageIndex")&&map.containsKey("pageSize")){
            Integer pageIndex = (Integer) map.get("pageIndex");
            Integer pageSize= (Integer) map.get("pageSize");
            pageIndex=pageSize*(pageIndex-1);
            map.replace("pageIndex",pageIndex);
        }
        return metaMapper.selectAllMetas(map);
    }
}
